#include "TokenBlock.h"
#include <argparse/argparse.hpp>
#include <cstdio>

// 生成字符串数组
static const char *SymbolTypeString[] = {
#define SYMBOL(a, b, c) b,
    SYMBOL_LIST
#undef SYMBOL
};

int main(int argc, char *argv[]) {
  argparse::ArgumentParser parser("LexicalAnalysis", "1.0");

  // 添加参数
  parser.add_argument("-i", "--input").help("Input file path").required();
  parser.add_argument("-o", "--output").help("Output file path");

  try {
    parser.parse_args(argc, argv);
  } catch (const std::runtime_error &err) {
    std::cerr << err.what() << std::endl;
    std::cerr << parser; // 打印帮助信息
    return 1;
  }

  // input
  std::string input_filename = parser.get<std::string>("--input");
  FILE *input_fp = fopen(input_filename.c_str(), "r");
  if (!input_fp) {
    fprintf(stderr, "%s: Failed to open input file %s\n", argv[0],
            input_filename.c_str());
    return -1;
  }

  // output
  FILE *output_fp;
  if (parser.is_used("--output")) {
    std::string output_filename = parser.get<std::string>("--output");
    output_fp = fopen(output_filename.c_str(), "w");
    if (output_fp == NULL) {
      fprintf(stderr, "%s: Failed to open output file %s\n", argv[0],
              output_filename.c_str());
      return -1;
    }
  } else {
    output_fp = stdout;
  }

  struct TokenBlock *tokens = get_typed_tokens(input_fp);
  fclose(input_fp);

  // 输出到文件
  for (struct TokenBlock *p = tokens; p != NULL; p = p->nextBlock) {
    fprintf(output_fp, "(%s, %s)\n", SymbolTypeString[p->sym], p->token);
  }
  fclose(output_fp);

  // 释放TokenBlock链表内存
  free_TokenList(tokens);

  return 0;
}
